package client;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;

public class Client {
	private String name;
	private Socket socket;
	
	public Client(String name) {
		this.name = name;
	}
	
	public void connect() throws IOException{
		socket = new Socket("localhost", 1234);
	}
	
	public void close() throws IOException{
		if (socket != null) socket.close();
	}
	
	public void send(String message) throws IOException{
		OutputStream os = socket.getOutputStream();
		
		int messageLength = message.length();
		byte [] messageLengthInByte = ByteBuffer.allocate(4).putInt(messageLength).array();
		
		// send 4 bytes for length
		os.write(messageLengthInByte);
		
		byte [] dataInByte = message.getBytes();
		
		// send data 
		os.write(dataInByte);
	}
	
	public String receive() throws IOException{
		InputStream is = socket.getInputStream();
		
		byte [] messageLengthInByte = new byte[4];
		
		// read 4 bytes for length
		is.read(messageLengthInByte);
		int messageLength = ByteBuffer.wrap(messageLengthInByte).getInt();
		
		byte [] messageInByte = new byte[messageLength];
		// read data
		is.read(messageInByte);
		String message = new String(messageInByte);
		return message;
	}
	
	public void sendTo(String des, String message) throws IOException{
		String sendMessage = des + ";" + message;
		send(sendMessage);
	}
	
	public static void main(String[] args) {
		Client client1 = new Client("Client 1");
		Client client2 = new Client("Client 2");
		
		try {
			// connect to server
			client1.connect();
			System.out.println("Client1 ket noi thanh cong");
			client2.connect();
			System.out.println("Client2 ket noi thanh cong");

			// register to server
			client1.sendTo("Server", client1.name);
			System.out.println("Client1 dang ky thanh cong voi server");
			client2.sendTo("Server", client2.name);
			System.out.println("Client2 dang ky thanh cong voi server");
			
			// client 1 send to client 2
			client1.sendTo("Client 2", "Hello Client 2, i'm Client 1");
			System.out.println("Client1 da gui tin nhan thanh cong");
			
			// client 2 send to client 1
//			client2.sendTo("Client 1", "Hello Client 1, i'm Client 2");
//			System.out.println("Client2 da gui tin nhan thanh cong");
			
			// client 1 receive message from client 2
//			System.out.println(client1.receive());

			// client 2 receive message from client 1
			System.out.println(client2.receive());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}